<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="photograph"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>拍照</title>
    <style type="text/css">
    .hide {
            display: none;
        }


    </style>
</head>
<body>
<video id="video" autoplay style="width: 480px;height: 320px" class="hide"></video>
<div>
    <button id="openN" onclick="handleOpen()">打开摄像头</button>
    <button id="closeN" onclick="handleClose()">关闭摄像头</button>
    <button id="capture" onclick="handleClickCapture()">拍照</button>
</div>

<!-- 展示拍摄的照片：画布 -->
<canvas id="canvas" width="480" height="320" class="hide"></canvas>
<div>
    <button id="usePhoto" onclick="usePhoto()" class="hide">使用照片</button>
</div>


<form method="post" enctype="multipart/form-data" id="file_upload">
    <p>
        <input type="button" value="添加椒盐噪声" onclick="pepperAndSalt()"/>
    </p>
    <p>
        <input type="button" value="裁剪图像" onclick="clip()"/>
    </p>
    </p>
    <p>处理后图片：</p>
    <span id="image-after"></span>
    <p>
        <input type="button" value="下载图片" onclick="save()"/>
    </p>
</form>
</body>

<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script type="text/javascript">
    var video = document.getElementById('video');
    var capture = document.getElementById('capture');
    var ctx = document.getElementById('canvas').getContext('2d');
    var usePhoto = document.getElementById('usePhoto')

    let file;

    /**
     * 调用用户媒体设备
     * @param constraints 配置信息
     * @param success 成功回调函数
     * @param error 失败回调函数
     */
    function getUserMediaToPhoto(constraints, success, error) {
        if (navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            navigator.webkitGetUserMedia(constraints, success, error);
        } else if (navigator.mozGetUserMedia) {
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            navigator.getUserMedia(constraints, success, error);
        }
    }

    /**
     * 成功回调函数
     * @param stream 视频流
     */
    function success(stream) {
        var CompatibleURL = window.URL || window.webkitURL;
        try {
            video.src = CompatibleURL.createObjectURL(stream);
        } catch (e) {
            video.srcObject = stream;
        }
        video.play();
    }

    /**
     * 失败回调
     * @param error 错误对象
     */
    function error(error) {
        console.log('无法访问媒体设备', error);
    }

    // 打开摄像头
    window.handleOpen = function (){
         if (navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia) {
            $("#video").removeClass("hide");
            $("#video").removeClass("hide");
            getUserMediaToPhoto({video: {width: 480, height: 320}}, success, error);
        } else {
            alert('不支持访问用户媒体设备');
        }
    }

    /**
     * 拍照按钮点击事件
     */
    function handleClickCapture() {
        $("#canvas").removeClass("hide");
        $("#usePhoto").removeClass("hide");
        //使在画布上显示
        ctx.drawImage(video, 0, 0, 480, 320);
    }

    // 关闭摄像头
    function handleClose(){
        video.srcObject.getTracks()[0].stop();
        video.className += 'hide';
    }

    // 使用拍的照片
    window.usePhoto = function (){
        video.srcObject.getTracks()[0].stop();
        $("#video").addClass("hide");
        //获取图片，这里获取到的是base64格式的文件
        var urlData = ctx.canvas.toDataURL();
        //base64转化为file
        let arr = urlData.split(',');
        let mime = arr[0].match(/:(.*?);/)[1];
        let bytes = atob(arr[1]);
        let n = bytes.length
        let ia = new Uint8Array(n);
        while (n--) {
            ia[n] = bytes.charCodeAt(n);
        }
        file = new File([ia], 'new.jpg', { type: mime });
    }

    // 保存图片
    function save() {
        var after = document.getElementById("after");
        if (!after) {
            alert("图片还未处理！")
            return false;
        }
        var url = after.src; // 获取图片地址
        var a = document.createElement('a'); // 创建一个a节点插入的document
        var event = new MouseEvent('click') // 模拟鼠标click点击事件
        a.download = '处理后图片.png' // 设置a节点的download属性值
        a.href = url; // 将图片的src赋值给a节点的href
        a.dispatchEvent(event)
    }
    // 椒盐噪声
    function pepperAndSalt() {
        var formData = new FormData;
        formData.append("image", file);
        $.ajax({
            url: 'pepperAndSalt', //请求路径
            type: 'POST', // 请求类型
            data: formData, // 请求数据
            headers: {"X-CSRFToken": $.cookie('csrftoken')},
            dataType: "text", // 返回数据格式
            contentType: false, //表示不处理数据
            processData: false,
            async: false,
            cache: false,
            success: function (data) {
                if (data != null){
                    //console.log("返回的数据："+data)
                    $('#image-after').append("<img class='image' id='after' src="+'"data:image/jpg;base64,'+data+'">')
                }
                if (data == null){
                    console.log("返回数据为空")
                }
            },
            error: function (data) {
                console.log("数据返回失败")
                console.log(data);
            }
        });

    }

</script>
</html>